import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wanxiang_app/bean/normal_entity.dart';
import 'package:wanxiang_app/pages/msg/chat.dart';
import 'package:wanxiang_app/pages/my/charge.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import 'package:wanxiang_app/widgets/account_textField2.dart';
import 'package:wanxiang_app/widgets/money_textField.dart';
import '../../bean/service_list_entity.dart';
import '../../bean/simple_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:get/get.dart';

import '../../widgets/simple_dialog.dart';

class KanjiaController extends GetxController{


  String channel_id = '';
  String goods_id = '';
  String price = '';
  String kan_id = '';
  @override
  void onInit() {
    super.onInit();
    Map map = Get.arguments;
    channel_id = map['channel_id'];
    goods_id = map['goods_id'];
    price = map['price'];
    if(map['kan_id']!=null){
      kan_id = map['kan_id'];
    }
    lowPrice = double.parse((double.parse(price)*0.6).toStringAsFixed(2));
    print(lowPrice);
    update();
  }
  double lowPrice = 0.0;

  bool checked = true;
  changeCheck(){
    checked = !checked;
    update();
  }

  @override
  void onClose() {
    super.onClose();
  }
  var inputPrice = '0'.obs;
   List<ServiceListData> list = [];
   late BuildContext mContext;
   void _kan(){
     showDialog(context: mContext, builder: (BuildContext context1) {
       return MySimpleDialog(callBack: (String content) {
         if(content == 'cancel'){
           // _PayKanjia();
           Navigator.pop(context1);
         }else if(content == 'sure'){
           Navigator.pop(context1);
           Get.to(()=>ChargePage(),arguments: {
             "kan_id":kan_id,
             "user_name":UserUtil.getUSER()?.userName,
             "new_price":inputPrice.value,
             "deposit_price":'20',
             "channel_id":channel_id,
             "goods_id":goods_id,
             "url":ServiceUrl.kanPay,
             "price":'20',
             "from":'kanjiaOrder',
             "readOnly":true
           },preventDuplicates:false);

         }
       },
         msg: "要支付意向金吗？",
         cancelText: '暂不支付',
         sureText: "立即支付",
       );
     });
   }
  void _PayKanjiaOrderAgain(){
    DioManager.getInstance().post(ServiceUrl.getBargainingBuyer,{
      "user_name":UserUtil.getUSER()?.userName,
      "bargaining_id":kan_id,
      'sell_price':inputPrice.value
    }, (data) async {
      if(data.startsWith('{')){
        SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
        ToastUtil.show(bannerEntity.msg);
      }else{
      }
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _PayKanjia(){
    DioManager.getInstance().post(ServiceUrl.kanOrder,{
      "user_name":UserUtil.getUSER()?.userName,
      "buy_type":"3",
      "new_price":inputPrice,
      "deposit_price":"0",
      "channel_id":channel_id,
      "goods_id":goods_id,
    }, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
    }, (error) {
      ToastUtil.show(error);
    });
  }

  void _Pay(){
    if(!checked){
      ToastUtil.show('请同意协议');
      return;
    }
    if(inputPrice.value.isEmpty){
      ToastUtil.show('请输入报价');
      return;
    }
    if(kan_id.isEmpty){
      _kan();
    }else{
      _PayKanjiaOrderAgain();
    }

    // DioManager.getInstance().post(ServiceUrl.kanPay,{
    //   "user_name":UserUtil.getUSER()?.userName,
    //   "buy_type":"3",
    //   "new_price":inputPrice,
    //   "deposit_price":'',
    //   "channel_id":channel_id,
    //   "goods_id":goods_id,
    // }, (data) async {
    //   ServiceListEntity bannerEntity = ServiceListEntity.fromJson(jsonDecode(data));
    //   list = bannerEntity.data;
    //   update();
    // }, (error) {
    //   ToastUtil.show(error);
    // });
  }
}


class KanjiaPage extends GetView<KanjiaController>  {
  late KanjiaController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {

    Get.lazyPut<KanjiaController>(() => KanjiaController());
    controller = Get.find();
    context = context1;
    controller.mContext = context1;
    return GetBuilder<KanjiaController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '砍价购买',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }
  Widget _content(){
    return SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(left: 20.w,top: 20.h,right: 20.w,bottom: 20.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text('报价',style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: 15.sp
                  ),),
                  Text('*',style: TextStyle(
                      color: Color(0xFFF43F50),
                      fontSize: 15.sp
                  ),),
                ],
              ),
              Row(
                children: [
                  Text('当前价格为',style: TextStyle(
                      color: Color(0xFF666666),
                      fontSize: 13.sp
                  ),),
                  Text('${ controller.price}',style: TextStyle(
                      color: Color(0xFFFF0000),
                      fontSize: 15.sp
                  ),),
                  Text('元,报价区间为',style: TextStyle(
                      color: Color(0xFF666666),
                      fontSize: 13.sp
                  ),),
                  Text('${controller.lowPrice}-${ controller.price}',style: TextStyle(
                      color: Color(0xFFFF0000),
                      fontSize: 15.sp
                  ),),
                  Text('元',style: TextStyle(
                      color: Color(0xFF666666),
                      fontSize: 13.sp
                  ),),

                ],
              ),

              SizedBox(height: 22.h,),
            Container(
              height: 48.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6.r)
              ),
              child: MoneyTextField(key: ValueKey('key'),hitText: '请输入报价', inputColor:0xFFF9F9F9, contentStrCallBack: (String content) {
                if(content.isEmpty){
                  controller.inputPrice.value = '0';
                }else{
                  controller.inputPrice.value = content;
                }

              },

              )
            ),
              SizedBox(height: 25.h,),
              Row(
                children: [
                  Text('意向金注意事项*',style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: 15.sp,
                    fontWeight: FontWeight.bold
                  ),),
                  Text('*',style: TextStyle(
                      color: Color(0xFF007BE5),
                      fontSize: 15.sp
                  ),),
                ],
              ),
              SizedBox(height: 6.h,),
              Row(
                children: [
                  Text('1、',style: TextStyle(
                      color: Color(0xFF666666),
                      fontSize: 13.sp
                  ),),
                  Text('报价金额不能低于商品价格的60%；',style: TextStyle(
                      color: Color(0xFF007BE5),
                      fontSize: 15.sp
                  ),),
                ],
              ),
              SizedBox(height: 3.h,),
              Text('2、重新报价需取消原报价；',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 15.sp
              ),),
              SizedBox(height: 3.h,),
              Text('3、砍价需支付20元的意向金，砍价失败原路退回，砍价成功抵扣号款',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 15.sp
              ),),
              SizedBox(height: 3.h,),
              Text('4、砍价成功因个人原因取消意向金不退，平台和卖家各50%；',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 15.sp
              ),),
              SizedBox(height: 3.h,),
              Text('5、重新报价时需再次支付意向金，支付后将原路退回先前支付的意向金；',style: TextStyle(
                  color: Color(0xFF666666),
                  fontSize: 15.sp,

              ),),
              SizedBox(height: 54.h,),
              Obx(() =>        InkWell(
                  onTap: (){
                    if(double.parse(controller.inputPrice.value)>=controller.lowPrice &&  double.parse(controller.inputPrice.value)<=double.parse(controller.price)){
                      controller._Pay();
                    }else{
                      ToastUtil.show('请输入正确的报价');
                    }

                  },
                  child:  Container(
                    height: 42.h,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: (double.parse(controller.inputPrice.value)>=controller.lowPrice &&  double.parse(controller.inputPrice.value)<=double.parse(controller.price))?  Color(0xFF007BE5): Color(0xFFCACBCC),
                        borderRadius: BorderRadius.circular(22.r)
                    ),
                    child: Text('确定',style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp
                    ),),
                  )
              )),

              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                      value: controller.checked,
                      onChanged: (value) {
                        controller.changeCheck();
                      }),
                  Text(
                    '同意上述',
                    style: TextStyle(
                        color: Color(0xFF666666), fontSize: 13.sp),
                  ),
                  InkWell(
                      onTap: () {},
                      child: Text(
                        '意向金注意事项',
                        style: TextStyle(
                            color: Color(0xFF007BE5), fontSize: 13.sp),
                      )),
                ],
              )
            ],
          ),
        )
    ) ;
  }











}